<template>
  <div id="register">
    <el-dialog title="注册" width="300px" center :visible.sync="isRegister">
      <el-form
        :model="RegisterUser"
        :rules="rules"
        status-icon
        ref="ruleForm"
        class="demo-ruleForm"
      >
        <el-form-item prop="name">
          <el-input
            prefix-icon="el-icon-user-solid"
            placeholder="请输入账号"
            v-model="RegisterUser.name"
          ></el-input>
        </el-form-item>
        <el-form-item prop="pass">
          <el-input
            prefix-icon="el-icon-view"
            type="password"
            placeholder="请输入密码"
            v-model="RegisterUser.pass"
          ></el-input>
        </el-form-item>
        <el-form-item prop="confirmPass">
          <el-input
            prefix-icon="el-icon-view"
            type="password"
            placeholder="请再次输入密码"
            v-model="RegisterUser.confirmPass"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button size="medium" type="primary" @click="Register" style="width:100%;">注册</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: "MyRegister",
  props: ["register"],
  data() {
    // 帐号校验
    let validateName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("咋不输用户名捏？"));
      }
      const userNameRules = /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/;
      if (userNameRules.test(value)) {
        // 判断数据库中是否存在该用户名
        this.$axios
          .post("users/findUserName", {
            userName: this.RegisterUser.name
          })
          .then(res => {
            // 001 代表不存在，可以注册
            if (res.code == "001") {
              this.$refs.ruleForm.validateField("checkPass");
              return callback();
            } else {
              return callback(new Error(res.msg));
            }
          })
          .catch(err => {
            return Promise.reject(err);
          });
      } else {
        return callback(new Error("字母开头,长度5~16之间,允许字母数字下划线"));
      }
    };
    // 密码校验
    let validatePass = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("咋不输密码捏？"));
      }
      // 密码以字母开头,长度在6-18之间,允许字母数字和下划线
      const userpassRules = /^[a-zA-Z]\w{5,17}$/;
      if (userpassRules.test(value)) {
        return callback();
      } else {
        return callback(
          new Error("字母开头,长度6-18之间,允许字母数字和下划线")
        );
      }
    };
    // 确认密码校验
    let validateConfirmPass = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请再次输入密码"));
      }
      if (value === this.RegisterUser.pass) {
        return callback();
      } else {
        return callback("两次输入的密码不一致");
      }
    };

    return {
      isRegister: false, // 控制注册组件是否显示
      RegisterUser: {
        name: "",
        pass: "",
        confirmPass: ""
      },
      // 校验规则
      rules: {
        name: [{ validator: validateName, trigger: "blur" }],
        pass: [{ validator: validatePass, trigger: "blur" }],
        confirmPass: [{ validator: validateConfirmPass, trigger: "blur" }]
      }
    };
  },
  watch: {
    register(val) {
      if (val) {
        this.isRegister = val;
      }
      
    },
    isRegister(val) {
      // 双向传值，改变父组件的传来的register值（父组件的绑定方式需要是这样:register.sync="xxx"）
      this.$emit("update:register", val);
    }
  },
  methods: {
    Register() {
      // element的自定义表单校验规则
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.$axios
            .post("users/register", {
              userName: this.RegisterUser.name,
              password: this.RegisterUser.pass
            })
            .then(res => {
              // "001" 代表注册成功，其他均为失败
              if (res.code === "001") {
                // 隐藏注册组件
                this.isRegister = false;
                this.notifySucceed(res.msg);
              } else {
                // 弹出注册失败信息
                this.notifyError(res.msg);
              }
            })
            .catch(err => {
              return Promie.reject(err);
            });
        } else {
          return false;
        }
      });
    }
  }
};
</script>
<style>
</style>